<?php

/**
 * 计划任务：命令行入口，建议 10 分钟左右运行一次。
 */
class CronTaskCommand extends ConsoleCommand
{
	private $_lockFile, $_lockFd;

	public function getHelp()
	{
		return <<<EOF
用法
  yiic crontask

说明
  执行计划任务（需自行扩展实现）

EOF;
	}

	public function actionIndex()
	{
		$tasks = Task::model()->findAllToBeRun();
		Yii::log('Load tasks to be run ... ' . count($tasks));
		foreach ($tasks as $task) {
			TaskRouter::runTask($task);
		}
	}

	protected function beforeAction($action, $params)
	{
		$file = Yii::getPathOfAlias('application.runtime.lock-') . __CLASS__;
		if (($fd = @fopen($file, 'a')) && flock($fd, LOCK_EX | LOCK_NB)) {
			$this->_lockFd = $fd;
			$this->_lockFile = $file;
		} else {
			Yii::log('Unable to get locker, maybe other process running', CLogger::LEVEL_WARNING);
			return false;
		}
		return parent::beforeAction($action, $params);
	}

	protected function afterAction($action, $params, $exitCode = 0)
	{
		if ($this->_lockFd) {
			@flock($this->_lockFd, LOCK_UN);
			@fclose($this->_lockFd);
			@unlink($this->_lockFile);
			$this->_lockFd = null;
			$this->_lockFile = null;
		}
		parent::afterAction($action, $params, $exitCode);
	}
}
